<?php
namespace Home\Controller;
use Think\Controller;

class BuyGoldController extends Controller {
    public function index(){
        $this->display(':buygold');
    }

    public function createorder() {
        $charaname = $_POST['charaname'];
        $goldnum = $_POST['goldnum'];

        if (!is_numeric($goldnum)) {
            $this->error('参数错误');
        }


        if (!characterExists($charaname)) {
            $this->error('角色不存在');
        }

        $money = intval($goldnum) * C('GOLD_PRICE');

        $orderId = genOrderId($charaname, $money);
        if (!$this->createorder($orderId, $charaname, $money)) {
            $this->error('创建订单失败');
        }

        $this->assign('charaname', $charaname);
        $this->assign('goldnum', $goldnum);
        $this->assign('money', $money);
        $this->assign('moneyStr', ($money / 100) . ' 圆');
        $this->assign('orderId', $orderId);
        $this->display(':createorder');
    }

    public function pay() {
        $charaname = $_POST['charaname'];
        $goldnum = $_POST['goldnum'];
        $money = $_POST['money'];
        $orderId = $_POST['orderid'];

        if (!is_numeric($goldnum)) {
            $this->error('参数错误');
        }

        if (!is_numeric($money)) {
            $this->error('参数错误');
        }

        $goldnum = intval($goldnum);
        $money = intval($money);

        if ($money != ($goldnum * C('GOLD_PRICE'))) {
            $this->error('参数错误');
        }

        ///////////////////////////////////////////////////////////////////////
        // PINGPP
        vendor('pingpp.init');

        $api_key = 'sk_live_4er5SSef5WXTiLGCCOn54GaH';
        $app_id = 'app_anPaHKP40K08TC8G';

        $body = $_POST['ordbody'];          // 课程ID
        $channel = 'alipay_pc_direct';      // 付费渠道
        $out_trade_no = $_POST['orderId'];  // 订单号

        // 检查渠道，必须检查
        if (empty($channel) || empty($totalmoney)) {
            echo 'channel or amount is empty';
            exit();
        }

        // 渠道附加参数
        $extra = array();
        switch ($channel) {
            case 'alipay_pc_direct':
                $extra = array(
                    'success_url' => C('NOTIFY_URL')
                );
                break;
        }

        // 生成Charge对象
        \Pingpp\Pingpp::setApiKey($api_key);
        try {
            $ch = \Pingpp\Charge::create(
                array(
                    'subject'   => $goldnum . '金币',
                    'body'      => array('charaname'=>$charaname, 'gold'=>$goldnum),
                    'amount'    => $money,  //订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
                    'order_no'  => $orderId,// 推荐使用 8-20 位，要求数字或字母，不允许其他字符
                    'currency'  => 'cny',
                    'extra'     => $extra,
                    'channel'   => $channel,// 支付使用的第三方支付渠道取值，请参考：https://www.pingxx.com/api#api-c-new
                    'client_ip' => $_SERVER['REMOTE_ADDR'],// 发起支付请求客户端的 IP 地址，格式为 IPV4，如: 127.0.0.1
                    'app'       => array('id' => $app_id)
                )
            );

            // 跳到支付
            $this->assign('ch', $ch);
            $this->display(':pingpp');
        } catch (\Pingpp\Error\Base $e) {
            // 捕获报错信息
            if ($e->getHttpStatus() != NULL) {
                header('Status: ' . $e->getHttpStatus());
                echo $e->getHttpBody();
            } else {
                echo $e->getMessage();
            }
        }
    }

    function notify(){
        vendor('alipay.Corefunction');
        vendor('alipay.Md5function');
        vendor('alipay.Notify');

        $_POST = $_GET;

        $alipay_config=array(
            'partner' => C('ALIPAY_PARTNER'),
            'key' => C('ALIPAY_KEY'),
            'sign_type' => C('ALIPAY_SIGNTYPE'),
            'input_charset' => C('ALIPAY_CHARSET'),
            'cacert' => C('ALIPAY_CACERT'),
            'transport' => 'ALIPAY_TRANSPORT',
        );
        $alipayNotify = new  \  AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {
            if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                $orderId = $_POST['out_trade_no'];

                $body = $_POST['body'];
                $charaname = $body['charaname'];
                $goldnum = intval($body['gold']);

                updateOrder($orderId, 1);
                if (!sendGoldMail($charaname, $goldnum)) {
                    echo '发送金币失败，请连接GM处理' . '<hr>';
                }

                echo '支付成功';
            } else {
                echo '支付失败';
            }
        } else {
            echo "<h1>非法通知数据</h1>";
        }
    }
}